package usercollect

import (
	"context"
	// "fmt"
	"strings"

	"mall/common/modelx"
	"mall/common/utils/pointy"
	"mall/service/forum/model"
	"mall/service/forum/rpc/internal/svc"
	"mall/service/forum/rpc/internal/utils/errorhandler"
	"mall/service/forum/rpc/types/forum"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetUserCollectListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetUserCollectListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetUserCollectListLogic {
	return &BackendGetUserCollectListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendGetUserCollectListLogic) BackendGetUserCollectList(in *forum.UserCollectListReq) (*forum.UserCollectListResp, error) {
	// logrus.Info(fmt.Sprintf("UserCollectListReq: %+v", in))

	var orderBys []string
	if len(in.OrderBy) > 0 {
		for _, orderBy := range in.OrderBy {
			var order = " ASC"
			if orderBy.Order == "1" {
				order = " DESC"
			}
			if orderBy.Field == "id" {
				orderBys = append(orderBys, model.ForumUserCollectColumns.CollectID+order)
			}
			if orderBy.Field == "createdAt" {
				orderBys = append(orderBys, model.ForumUserCollectColumns.CreatedAt+order)
			}
			if orderBy.Field == "updatedAt" {
				orderBys = append(orderBys, model.ForumUserCollectColumns.UpdatedAt+order)
			}
		}
	}

	var stati string
	if len(in.FilterBy) > 0 {
		for _, filterBy := range in.FilterBy {
			if filterBy.Field == "status" {
				stati = filterBy.In
			}
		}
	}

	var page uint64
	var pageSize uint64
	var restricted bool
	filterMap := make(map[string]map[string][]any)
	resp := &forum.UserCollectListResp{}
	if in.UserId != nil && *in.UserId > 0 {
		filterMap[model.ForumUserCollectColumns.UserID] = map[string][]any{
			"equalTo": []any{*in.UserId},
		}
	}
	if in.Ids != nil {
		if vals := modelx.UniqueInterfaces(*in.Ids, 64); len(vals) == 0 {
			return resp, nil
		} else {
			filterMap[model.ForumUserCollectColumns.CollectID] = map[string][]any{
				"in": vals,
			}
			restricted = true
		}
	}

	if !restricted {
		page = in.Page
		pageSize = in.PageSize
	}

	statusIn := modelx.UniqueInterfaces(stati, 32)
	statusMap := make(map[string][]any)
	if len(statusIn) > 0 {
		statusMap["in"] = statusIn
	}
	if in.Status != nil {
		statusMap["equalTo"] = []any{*in.Status}
	}
	filterMap[model.ForumUserCollectColumns.Status] = statusMap

	if in.ObjectId != nil {
		filterMap[model.ForumUserCollectColumns.ObjectID] = map[string][]any{
			"contain": []any{*in.ObjectId},
		}
	}
	if in.ObjectType != nil {
		filterMap[model.ForumUserCollectColumns.ObjectType] = map[string][]any{
			"contain": []any{*in.ObjectType},
		}
	}

	var startTimeIn []any
	var endTimeIn []any
	if in.StartTime != nil && len(strings.TrimSpace(*in.StartTime)) > 0 {
		if startTime, err := modelx.ParseLocalDate(strings.TrimSpace(*in.StartTime)); err == nil {
			startTimeIn = append(startTimeIn, startTime)
		}
	}
	if in.EndTime != nil && len(strings.TrimSpace(*in.EndTime)) > 0 {
		if endTime, err := modelx.ParseLocalDate(strings.TrimSpace(*in.EndTime)); err == nil {
			endTimeIn = append(endTimeIn, endTime)
		}
	}
	createdAtMap := make(map[string][]any)
	if len(startTimeIn) > 0 {
		createdAtMap["moreThanOrEqualTo"] = startTimeIn
	}
	if len(endTimeIn) > 0 {
		createdAtMap["lessThan"] = endTimeIn
	}
	filterMap[model.ForumUserCollectColumns.CreatedAt] = createdAtMap

	var orderBy string
	if len(orderBys) > 0 {
		orderBy = strings.Join(orderBys, ",")
	}
	res, count, err := l.svcCtx.UserCollect.GetList(l.ctx, model.M{
		"page":     page,
		"pageSize": pageSize,
		"orderBy":  orderBy,
	}, 1, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	resp.Total = uint64(count)
	if len(res) > 0 {
		for _, v := range res {
			resp.List = append(resp.List, &forum.UserCollectInfo{
				Id:         pointy.GetPointer(v.CollectID),
				UserId:     pointy.GetPointer(v.UserID),
				PlatformId: pointy.GetPointer(uint32(v.PlatformID)),
				ObjectId:   pointy.GetPointer(v.ObjectID),
				ObjectType: pointy.GetPointer(uint32(v.ObjectType)),
				Status:     pointy.GetPointer(uint32(v.Status)),
				CreatedAt:  pointy.GetPointer(modelx.FormatTime(v.CreatedAt, "")),
				UpdatedAt:  pointy.GetPointer(modelx.FormatTime(v.UpdatedAt, "")),
			})
		}
	}

	return resp, nil
}
